package com.free.semantic.core.funcimpl;

import com.free.semantic.common.ContextImpl;
import com.free.semantic.common.RelationItem;
import com.free.semantic.core.Context;
import com.free.semantic.core.RelationFunction;

public class MergeFuncImpl extends BaseFuncImpl {

    RelationItem first;
    RelationItem second;

    RelationFunction firstFunc;
    RelationFunction secondFunc;

    public MergeFuncImpl(RelationItem first, RelationItem second, RelationFunction firstFunc, RelationFunction secondFunc) {
        this.first = first;
        this.second = second;
        this.firstFunc = firstFunc;
        this.secondFunc = secondFunc;
    }

    @Override
    public void calculate(Context context) {

        ContextImpl contextFirst = new ContextImpl(first);
        for (String s : first.getSourceObjList()) {
            contextFirst.setValue(s, context.getListValue(s));
        }
        firstFunc.calculate(contextFirst);
        ContextImpl contextSecond = new ContextImpl(second);
        for (String s : second.getSourceObjList()) {
            if (s.equals(first.getDestObj())) {
                contextSecond.setValue(s, contextFirst.getListValue(s));
            } else {
                contextSecond.setValue(s, context.getListValue(s));
            }
        }
        secondFunc.calculate(contextSecond);
        setValue(context, contextSecond.getListValue(getRelationItem().getDestObj()));
    }

}
